<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="题目类型" prop="quType">
        <el-select
          v-model="queryParams.quType"
          placeholder="题目类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.qu_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="难度等级" prop="level">
        <el-select
          v-model="queryParams.level"
          placeholder="难度等级"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.qu_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="归属题库" prop="repoId">
        <el-select
          v-model="queryParams.repoId"
          placeholder="归属题库"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="dict in repoList"
            :key="dict.id"
            :label="dict.title"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="题目内容" prop="content">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入题目内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:qu:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:qu:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:qu:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="quList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="题目类型"
        align="center"
        width="100"
        prop="quType"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.qu_type" :value="scope.row.quType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="难度等级" width="100" align="center" prop="level">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.qu_level" :value="scope.row.level" />
        </template>
      </el-table-column> -->
      <el-table-column
        label="归属题库"
        width="120"
        align="center"
        prop="title"
      />
      <el-table-column label="题目内容" align="center" prop="content" />
      <!-- <el-table-column label="整题解析" align="center" prop="analysis" />
      <el-table-column label="题目备注" align="center" prop="remark" /> -->
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:qu:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:qu:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试题主对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="题目类型" prop="quType">
          <el-select
            v-model="form.quType"
            placeholder="题目类型"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.qu_type"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="难度等级" prop="level">
          <el-select
            v-model="form.level"
            placeholder="难度等级"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.qu_level"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="归属题库" prop="repoId">
          <el-select
            v-model="form.repoId"
            placeholder="归属题库"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in repoList"
              :key="dict.id"
              :label="dict.title"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目内容" prop="content">
          <el-input v-model="form.content" type="textarea" />
        </el-form-item>
        <div style="margin-bottom: 20px">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            plain
            @click="addSelect"
          >
            添加
          </el-button>
          <el-table
            :data="form.quAnswerVos"
            :border="true"
            style="width: 100%; margin-top: 15px"
          >
            <el-table-column label="是否答案" width="120" align="center">
              <template v-slot="scope">
                <el-checkbox v-model="scope.row.isRight">答案</el-checkbox>
              </template>
            </el-table-column>

            <el-table-column label="答案内容">
              <template v-slot="scope">
                <el-input v-model="scope.row.content" type="textarea" />
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="100px">
              <template v-slot="scope">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="removeItem(scope.$index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-form-item label="整题解析" prop="analysis">
          <el-input
            v-model="form.analysis"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="题目备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入题目备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-form
        ref="uploadForm"
        :model="upload"
        :rules="uploadRules"
        label-width="80px"
      >
        <!-- <el-form-item label="难度等级" prop="level">
          <el-select
            v-model="upload.level"
            placeholder="难度等级"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.qu_level"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="归属题库" prop="repoId">
          <el-select
            v-model="upload.repoId"
            placeholder="归属题库"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dict in repoList"
              :key="dict.id"
              :label="dict.title"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".docx, .doc, .xls, .xlsx"
        :headers="upload.headers"
        :action="
          upload.url +
          '?updateSupport=' +
          upload.updateSupport +
          '&level=' +
          upload.level +
          '&repoId=' +
          upload.repoId
        "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div>仅允许导入doc、docx 、xls、xlsx格式的文件</div>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline; margin-top: 10px"
            @click="importTemplate"
            >下载excel模板</el-link
          >
          <el-link
            type="primary"
            :underline="false"
            href="https://zc.e0s.cn/prod-api/profile/upload/2024/04/28/bebdd28b-17e9-461e-b9b3-b604fd4c7eae.jpeg"
            style="
              font-size: 12px;
              vertical-align: baseline;
              margin-top: 10px;
              margin-left: 25px;
            "
            >下载word模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQu, getQu, delQu, addQu, updateQu } from "@/api/business/qu";
import { listAllRepo } from "@/api/business/repo";
import { getToken } from "@/utils/auth";
export default {
  name: "Qu",
  dicts: ["qu_type", "qu_level"],
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 用户导入参数
      upload: {
        repoId: null,
        level: 1,
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/qu/import",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试题主表格数据
      quList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      repoList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        quType: null,
        level: null,
        image: null,
        content: null,
        remark: null,
        analysis: null,
        repoId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        quType: [
          { required: true, message: "题目类型不能为空", trigger: "change" },
        ],
        // level: [
        //   { required: true, message: "难度等级不能为空", trigger: "blur" },
        // ],
        content: [
          { required: true, message: "题目内容不能为空", trigger: "blur" },
        ],
        repoId: [
          { required: true, message: "归属题库不能为空", trigger: "blur" },
        ],
      },
      uploadRules: {
        // level: [
        //   { required: true, message: "难度等级不能为空", trigger: "blur" },
        // ],
        repoId: [
          { required: true, message: "归属题库不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    // console.log(
    //   String.fromCharCode(65 + 0),
    //   String.fromCharCode(65 + 1),
    //   String.fromCharCode(65 + 3),
    //   String.fromCharCode(65 + 4)
    // );
    this.getList();
    this.getrepoList();
  },
  methods: {
    /** 查询试题主列表 */
    getList() {
      this.loading = true;
      listQu(this.queryParams).then((response) => {
        this.quList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getrepoList() {
      listAllRepo().then((response) => {
        this.repoList = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        quType: null,
        level: 1,
        image: null,
        content: null,
        remark: null,
        analysis: null,
        repoId: null,
        quAnswerVos: [],
      };
      this.resetForm("form");
    },
    addSelect() {
      this.form.quAnswerVos.push({ isRight: false, content: "" });
    },
    removeItem(index) {
      this.form.quAnswerVos.splice(index, 1);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试题";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getQu(id).then((response) => {
        this.form = response.data;
        if (this.form.quAnswerVos.length) {
          this.form.quAnswerVos.forEach((row) => {
            if (row.isRight == 1) {
              row.isRight = true;
            } else {
              row.isRight = false;
            }
          });
        }
        this.open = true;
        this.title = "修改试题";
        console.log(this.form);
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form.quAnswerVos);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.quAnswerVos.length) {
            this.form.quAnswerVos.forEach((row) => {
              if (row.isRight) {
                row.isRight = 1;
              } else {
                row.isRight = 0;
              }
            });
          }
          if (this.form.id != null) {
            updateQu(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQu(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      console.log(222222, ids);
      console.log(this.ids);
      this.$modal
        .confirm("是否确认删除该试题？")
        .then(function () {
          return delQu(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/qu/export",
        {
          ...this.queryParams,
        },
        `qu_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "business/qu/importTemplate",
        {},
        `qu_template_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.repoId = null;
      this.upload.level = 1;
      this.upload.title = "导入试题";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs["uploadForm"].validate((valid) => {
        console.log(valid);
        if (valid) {
          this.$refs.upload.submit();
        }
      });
    },
  },
};
</script>
